package autogo

import (
	"log"
	"time"

	w32 "github.com/gonutz/w32/v2"
)

//鼠标键盘的绑定函数

// 设置按键之后的延时，给电脑一点反映时间，超过1秒的延时建议手动设置
const (
	KeyDelay = 1
)

// 设置鼠标操作（移动或点击）之后的延时，给电脑一点反映时间，超过1秒的延时建议手动设置
var (
	MouseDelay  = 1
	ScreenScale = 1
)

func Key(Vk uint16, Flags uint32) uint32 {
	ret := w32.SendInput(w32.KeyboardInput(w32.KEYBDINPUT{
		Vk:        Vk,
		Scan:      0,
		Flags:     Flags,
		Time:      0,
		ExtraInfo: 0,
	}))
	if ret == 0 {
		log.Fatal("Danger! The calling thread's last-error code: ", w32.GetLastError())
	}
	return ret
}

func KeyClick(Vk uint16) {
	Key(Vk, 0)
	Key(Vk, w32.KEYEVENTF_KEYUP)
	time.Sleep(time.Duration(KeyDelay) * time.Second)
}

// 一次按两个键，用于快捷键
func Key2Click(Vk1, Vk2 uint16) {
	Key(Vk1, 0)
	Key(Vk2, 0)
	Key(Vk2, w32.KEYEVENTF_KEYUP)
	Key(Vk1, w32.KEYEVENTF_KEYUP)
	time.Sleep(time.Duration(KeyDelay) * time.Second)
}

func KeyCopy() {
	Key2Click(w32.VK_LCONTROL, w32.VK_C)
}

func KeyPaste() {
	Key2Click(w32.VK_LCONTROL, w32.VK_V)
}

func Mouse(Flags uint32) uint32 {
	ret := w32.SendInput(w32.MouseInput(w32.MOUSEINPUT{
		Dx:        0,
		Dy:        0,
		MouseData: 0,
		Flags:     Flags,
		Time:      0,
		ExtraInfo: 0,
	}))
	if ret == 0 {
		log.Fatal("Danger! The calling thread's last-error code: ", w32.GetLastError())
	}
	return ret
}

func MouseMove(Dx int, Dy int) {
	hdc := w32.GetDC(w32.GetDesktopWindow())
	screenWidth := w32.GetDeviceCaps(hdc, w32.DESKTOPHORZRES)
	screenHeight := w32.GetDeviceCaps(hdc, w32.DESKTOPVERTRES)
	x := int32(Dx * 65552 / screenWidth)
	y := int32(Dy * 65552 / screenHeight)
	re := w32.SendInput(w32.MouseInput(w32.MOUSEINPUT{
		Dx:        x,
		Dy:        y,
		MouseData: 0,
		Flags:     w32.MOUSEEVENTF_MOVE | w32.MOUSEEVENTF_ABSOLUTE,
		Time:      0,
		ExtraInfo: 0,
	}))
	if re == 0 {
		log.Fatal("Danger! The calling thread's last-error code: ", w32.GetLastError())
	}
	KeyClick(w32.VK_CONTROL) //鼠标移动后显示一次鼠标位置
	time.Sleep(time.Duration(MouseDelay) * time.Second)
}

// 鼠标左键点击一下
func MouseClick() {
	Mouse(w32.MOUSEEVENTF_LEFTDOWN)
	Mouse(w32.MOUSEEVENTF_LEFTUP)
	time.Sleep(time.Duration(MouseDelay) * time.Second)
}

// 鼠标右键点击一下
func MouseClickR() {
	Mouse(w32.MOUSEEVENTF_RIGHTDOWN)
	Mouse(w32.MOUSEEVENTF_RIGHTUP)
	time.Sleep(time.Duration(MouseDelay) * time.Second)
}

// 鼠标移动到指定位置并左键点击一下
func MouseMoveClick(Dx int, Dy int) {
	MouseMove(Dx, Dy)
	MouseClick()
}

// 鼠标左键按下不放移动到指定像素抬起（选取文字或者移动某些东西）
func MouseDrag(Dx int, Dy int) {
	Mouse(w32.MOUSEEVENTF_LEFTDOWN)
	MouseMove(Dx, Dy)
	Mouse(w32.MOUSEEVENTF_LEFTUP)
}

// 鼠标移动到指定像素Sx, Sy，左键按下不放移动到指定像素Dx, Dy抬起（选取文字或者移动某些东西）
func MouseMoveDrag(Sx, Sy, Dx, Dy int) {
	MouseMove(Sx, Sy)
	Mouse(w32.MOUSEEVENTF_LEFTDOWN)
	MouseMove(Dx, Dy)
	Mouse(w32.MOUSEEVENTF_LEFTUP)
}

func Test() {
	Key2Click(w32.VK_LWIN, w32.VK_R)

}
